 //
//  LSNewHomeViewController.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/10/24.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSNewHomeViewController.h"
#import "LSHomeDataManager.h"
#import "KZUserCenterVC.h"
#import "LSRadarView.h"
#import "LSPagedFlowView.h"
#import "KZSoundTool.h"
#import "XPQGifView.h"
#import "KZHomeBgView.h"
#import "LSSoundPlayer.h"
#import "IPhoneType.h"

@interface LSNewHomeViewController ()<LSPagedFlowViewDelegate,LSPagedFlowViewDataSource,CAAnimationDelegate>

@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) XPQGifView *gifImageView;

/**
 加载
 */
@property (nonatomic,strong) UIImageView *loadingImageView;

@property (nonatomic,strong) KZHomeBgView *bgview;

/**
 标题
 */
@property (nonatomic,strong) UILabel *titleLabel;

/**
 雷达
 */
@property (nonatomic,strong) LSRadarView *radarView;

/**
 颜色
 */
@property (nonatomic,strong) NSArray *colors;

/**
 背景gif
 */
@property (nonatomic,strong)  UIImageView *backgroundImageView;

/*
 智能分析中
 */
@property (nonatomic,strong) UILabel *tiplabel;

@property (nonatomic,assign) NSInteger pageNumber;

@property (nonatomic,strong) LSPagedFlowView *pageFlowView;

@property (nonatomic,strong) LSSoundPlayer *soundPlayer;

@end

@implementation LSNewHomeViewController

- (BOOL)checkPermission{
    
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) {
        AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {// 未询问用户是否授权
            AVAudioSession *audioSession = [AVAudioSession sharedInstance];
            if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
                [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                    if (granted) {
                        bCanRecord = YES;
                    } else {
                        bCanRecord = NO;
                    }
                }];
            }
        } else if(videoAuthStatus == AVAuthorizationStatusRestricted || videoAuthStatus == AVAuthorizationStatusDenied) {
            // 未授权
            [self showSetAlertView];
        } else{
            // 已授权
            NSLog(@"已授权");
        }
    }
    return bCanRecord;
}

//提示用户进行麦克风使用授权
- (void)showSetAlertView {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"麦克风权限未开启" message:@"麦克风权限未开启，请进入系统【设置】>【隐私】>【麦克风】中打开开关,开启麦克风功能" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *setAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //跳入当前App设置界面
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:setAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
    
    
};

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground) name:@"applicationWillEnterForeground" object:nil];

    self.view.backgroundColor = [UIColor whiteColor];

    [self checkPermission];
    
    // Do any additional setup after loading the view.
//    self.loadingImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight-kBottomPadding)];
//    NSMutableArray *images = [NSMutableArray array];
//    for (NSInteger i = 0; i<202; i++) {
//        if (i%2==0) {
//            NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"组 7_00%03ld",i] ofType:@"png"];
//            UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];
//            [images addObject:image];
//        }
//    }
//    self.loadingImageView.animationImages = images;
//    self.loadingImageView.animationDuration = 5;
//    self.loadingImageView.animationRepeatCount = 0;
//    [self.loadingImageView startAnimating];
//    [self.view addSubview:self.loadingImageView];
    
    self.gifImageView = [[XPQGifView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight-kBottomPadding)];
    [self.view addSubview:self.gifImageView];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"LS-加载4" ofType:@"gif"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    self.gifImageView.gifData = data;
    self.gifImageView.sleep = 0.5;
    [self.gifImageView start];
    self.gifImageView.contentMode = UIViewContentModeScaleAspectFill;
   
    double delayInSeconds = 0.5;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds *NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        //执行事件
        //[KZSoundTool playSound:KZSoundType_index_analyze];
        
        LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_index_analyze];
        self.soundPlayer = player;
    });
    
    self.tiplabel =[[UILabel alloc] initWithFrame:CGRectMake((kWidth-100)/2, kHeight-kBottomPadding-50,100,20)];
    self.tiplabel.textColor = [UIColor colorWithHex:0xbbbaba];
    [self.view addSubview:self.tiplabel];
    self.tiplabel.textAlignment = NSTextAlignmentCenter;
    self.tiplabel.font = FONT(15);
   // self.tiplabel.text = @"智能分析中...";
    
    UILabel *titleLabel = [[UILabel alloc] init];
    self.titleLabel = titleLabel;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.numberOfLines = 0;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = FONT(W(13));
    NSString *titleText = @"高考英语听说学习训练平台\n听说智能训练";
    NSRange range = [titleText rangeOfString:@"听说智能训练"];
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:titleText];
    [attr addAttributes:@{NSFontAttributeName:FONT(W(19)),NSForegroundColorAttributeName:[UIColor whiteColor]} range:range];
    titleLabel.attributedText = attr;
    [self.view addSubview:titleLabel];
    CGFloat top = 20;
    if (isPhoneX) {
        top = 44;
    }
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(top);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(W(160), W(40)));
    }];
    
    [self loadData];
}

- (void)loadData {
    LSHomeDataManager *manager =  [[LSHomeDataManager alloc] init];
    NSDictionary *dict = @{
                           @"SchoolID":KGetUserDefaults(@"SchoolID"),
                           @"XH":DR_UserInfo.UserID,
                           @"HTestID":KGetUserDefaults(@"TestLayer"),
                           @"SubjectID":@"S2-English"
                           };
    manager.requestParam = @{@"DictString":[NSObject objectToJson:dict]};
    self.dataArray = [NSMutableArray array];
    double delayInSeconds = 9.6;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds *NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        
        WeakObj(self);
        [manager requestWithCompltionSuccess:^(LSModelHome *model) {
            
            [selfWeak.dataArray addObjectsFromArray:model.InfoList.firstObject.WeakList];

            [selfWeak addHideAnimation:selfWeak.gifImageView];
            
            [selfWeak.tiplabel removeFromSuperview];
            selfWeak.tiplabel = nil;
            
           // [KZSoundTool stop];
            [selfWeak.soundPlayer stop];
            
            [selfWeak addChartView];
            
            UIImageView *imageView =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight-kBottomPadding)];
            selfWeak.backgroundImageView = imageView;
            imageView.image = [UIImage imageNamed:@"LS-背景图"];
            [selfWeak.view addSubview:imageView];
            [selfWeak.view insertSubview:imageView atIndex:0];
            
            KZHomeBgView *bgview = [[KZHomeBgView alloc] init];
            bgview.y = bgview.y + 50;
            selfWeak.bgview = bgview;
            [selfWeak.backgroundImageView addSubview:bgview];
            if (kWidth>414.0f) {
                bgview.y = bgview.y - 50;
            }
            [selfWeak addBYItemviews:@[@"LS-头像"] mode:ByNavigationItemModeImage position:ByNavigationItemPositionModeRight];
          
        } failuer:^(NSString *error) {
            
            
            
        }];
    });
    
}

#pragma mark - 添加蜘蛛图，曲线图
- (void)addChartView {
    dispatch_async(dispatch_get_main_queue(), ^{
        
        NSMutableArray *titles = [NSMutableArray array];
        NSMutableArray *values = [NSMutableArray array];
        NSMutableArray *standards = [NSMutableArray array];
        for (NSInteger i = 0; i<self.dataArray.count; i++) {
            
            LSweak *weak = self.dataArray[i];
           
            
            [titles addObject:[weak.AbiScoreType stringByReplacingOccurrencesOfString:@"量" withString:@""]];
            
            NSString *value = [weak.ZDScoreString componentsSeparatedByString:@","].lastObject;
            [values addObject:value];
            
            //模拟
           // weak.GoodScore = @"60";
            [standards addObject:weak.GoodScore];
        }
        LSRadarView *radarView = [[LSRadarView alloc] initWithFrame:CGRectMake((self.view.frame.size.width-W(300))/2,90,W(300),W(300))];
        radarView.standardvalue_array = standards;
        radarView.value_array = values;
        radarView.title_array = titles;
        [self.view addSubview:radarView];
        self.radarView = radarView;
        [radarView startMainAnimation];
        
        _colors = @[[UIColor whiteColor] , [UIColor whiteColor] , [UIColor whiteColor] , [UIColor whiteColor] , [UIColor whiteColor]];
        LSPagedFlowView *pageFlowView = [[LSPagedFlowView alloc] initWithFrame:CGRectMake(0,W(300)+100,self.view.frame.size.width, self.view.frame.size.width *0.78)];
        self.pageFlowView = pageFlowView;
        if (kWidth>414.0f) {
            radarView.y = 50;
            pageFlowView.y = W(220);
        } else if (iPhone5S) {
            pageFlowView.y = W(300)+80;
        }
        
        BOOL isiPhoneX = [IPhoneType judge_iPhoneX];
        if (isiPhoneX) {
            radarView.y = 150;
            pageFlowView.y = W(300)+150;
        }
        
        pageFlowView.delegate = self;
        pageFlowView.dataSource = self;
        pageFlowView.minimumPageAlpha = 0.1;
        pageFlowView.isCarousel = NO;
        pageFlowView.orientation = LSPagedFlowViewOrientationHorizontal;
        pageFlowView.isOpenAutoScroll = NO;
        [pageFlowView reloadData];
        [self.view addSubview:pageFlowView];
        
    });
}


#pragma mark - NewPagedFlowView Delegate
- (CGSize)sizeForPageInFlowView:(LSPagedFlowView *)flowView {
    return CGSizeMake(self.view.frame.size.width * 338/375, self.view.frame.size.width * 226/375);
}

- (void)didSelectCell:(UIView *)subView withSubViewIndex:(NSInteger)subIndex {
    
    NSLog(@"点击了第%ld张图",(long)subIndex + 1);
    
    // self.indicateLabel.text = [NSString stringWithFormat:@"点击了第%ld张图",(long)subIndex + 1];
}

- (void)didScrollToPage:(NSInteger)pageNumber inFlowView:(LSPagedFlowView *)flowView {
    
    NSLog(@"ViewController 滚动到了第%ld页",pageNumber);
    _pageNumber = pageNumber;
    LSBannerSubView *bannerView = [flowView viewWithTag:1000+pageNumber];
    [bannerView startAnimation];
    
    [self.radarView startMoveCircle:pageNumber];
    
    //[KZSoundTool playSound:KZSoundType_paging];
    LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_paging];
    self.soundPlayer = player;
    
}

#pragma mark - NewPagedFlowView Datasource
- (NSInteger)numberOfPagesInFlowView:(LSPagedFlowView *)flowView {
    return 5;
}

- (LSBannerSubView *)flowView:(LSPagedFlowView *)flowView cellForPageAtIndex:(NSInteger)index{
    LSBannerSubView *bannerView = [flowView dequeueReusableCell];
    if (!bannerView) {
        bannerView = [[LSBannerSubView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width * 338/375, self.view.frame.size.width * 226/375)];
        bannerView.title = self.radarView.title_array[index];
        bannerView.weak = self.dataArray[index];
        bannerView.tag = 1000+index;
        bannerView.layer.cornerRadius = 8;
        bannerView.layer.masksToBounds = YES;
    }
    
    bannerView.backgroundColor = _colors[index];
    if (index==0) {
        [bannerView startAnimation];
    }
    
    return bannerView;
}

#pragma mark - 按钮点击事件
- (void)rightItemsAction:(NSInteger)rightIndex {
    if (rightIndex==0) {
        KZUserCenterVC *vc = [[KZUserCenterVC alloc] init];
        [self push:vc];
       // self.isPushUserCenter = YES;
    }
}

#pragma mark - 生命周期
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
//    [_backgroundImageView removeFromSuperview];
//    _backgroundImageView = nil;
    
    [self.bgview stopRain];
    
    [self.soundPlayer stop];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    if (self.soundPlayer) {
        [self.soundPlayer stop];
    }
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 设置导航栏的默认属性(默认为不透明、黑色状态栏)
    [self setNaviAttributeWithTranslucent:YES stateBarLightContent:YES];
    
    if (self.bgview) {
        [self.bgview startRain];
    }
    
    if (self.radarView) {
        [self.radarView startIndicatorViewScale];
    }
    
    for(NSInteger i = 0;i<5;i++) {
        LSBannerSubView *bannerView = [self.pageFlowView viewWithTag:1000+i];
        [bannerView startScale];
    }
    
    //    [imageView gif:@"LS-背景3"];
    //    [self.view addSubview:imageView];
    //    [self.view insertSubview:imageView atIndex:0];
    //
    //    [self.view bringSubviewToFront:self.radarView];
    // if (self.backgroundImageView) {
    
    //  }
}

- (void)applicationWillEnterForeground {
    if (self.bgview) {
        [self.bgview startRain];
    }
    
    if (self.radarView) {
        [self.radarView startIndicatorViewScale];
    }
    
    for(NSInteger i = 0;i<5;i++) {
        LSBannerSubView *bannerView = [self.pageFlowView viewWithTag:1000+i];
        [bannerView startScale];
    }

}


//消失动画
- (void)addHideAnimation:(UIView*)view {
    
    CABasicAnimation * fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeAnim.delegate = self;
    fadeAnim.fromValue = @(1);
    fadeAnim.toValue = @(0);
    fadeAnim.repeatCount = 1;
    fadeAnim.duration = 0.6;
    [view.layer addAnimation:fadeAnim forKey:@"Hide"];
    view.alpha = 0;
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    
    [self.gifImageView stop];
    [self.gifImageView removeFromSuperview];
    self.gifImageView = nil;
}

//更新弱点
- (void)updateData {
    
//    LSHomeDataManager *manager = [[LSHomeDataManager alloc] init];
//    NSDictionary *dict = @{
//                           @"SchoolID":KGetUserDefaults(@"SchoolID"),
//                           @"XH":DR_UserInfo.UserID,
//                           @"HTestID":KGetUserDefaults(@"TestLayer"),
//                           @"SubjectID":@"S2-English",
//                           @"WeakID":self.weekID?self.weekID:@""
//                           };
//    manager.requestParam = @{@"DictString":[NSObject objectToJson:dict]};
//    WeakObj(self);
//    [manager updateWithCompltionSuccess:^(LSModelHome *model) {
//        [self.dataArray removeAllObjects];
//        [self.dataArray addObjectsFromArray:model.InfoList.firstObject.WeakList];
//        NSArray *array = model.InfoList.firstObject.WeakList;
//        [selfWeak reloadHomeViewWithArray:array];
//
//    } failuer:^(NSString *error) {
//
//    }];
    
}

@end
